package com.jsh.erp.service.promotionHead;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.*;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.CollectionCombineUtils;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.jsh.erp.utils.Tools.getCenternTime;


@Service
public class PromotionHeadService {
    private Logger logger = LoggerFactory.getLogger(PromotionHeadService.class);
    @Resource
    private PromotionHeadMapper promotionHeadMapper;

    @Resource
    private PromotionHeadMapperEx promotionHeadMapperEx;
    @Resource
    private PromotionItemMapper promotionItemMapper;
    @Resource
    private PromotionDepotMapper promotionDepotMapper;
    @Resource
    private PromotionSupplierMapper promotionSupplierMapper;
    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private PromotionGiftMapper promotionGiftMapper;
    @Resource
    private SystemConfigService systemConfigService;

    public PromotionHead getPromotionHead(String id) throws Exception {
        PromotionHead result = null;
        try {
            result = promotionHeadMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<PromotionHeadWithSupplier> select(String name, String promotionType, String startTime, String endTime, String promotionState, int offset, int rows) throws Exception {
        List<PromotionHeadWithSupplier> resList = new ArrayList<PromotionHeadWithSupplier>();
        List<PromotionHeadWithSupplier> list = null;
        try {
            startTime = Tools.parseDayToTime(startTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = promotionHeadMapperEx.selectByPromotionHead(name, promotionType, startTime, endTime, promotionState, offset, rows);
            if (null != list) {
                for (PromotionHeadWithSupplier dh : list) {
                    dh.setStartTimeStr(getCenternTime(dh.getStartTime()));
                    dh.setEndTimeStr(getCenternTime(dh.getEndTime()));
                    dh.setCreateTimeStr(getCenternTime(dh.getCreateTime()));
                    dh.setStatus("0");
                    if (null !=dh.getCustom11() &&dh.getCustom11()==3){
                        if (null != dh.getHoldSupplier() && dh.getHoldSupplier()==2){
                            List<PromotionSupplier> supplierList = getSupplierId(dh.getId());
                            Set<String> existsSets = Sets.newHashSet();
                            if (supplierList != null && supplierList.size()>0){
                                supplierList.forEach(existsVO -> {
                                    existsSets.add(existsVO.getSupplierId());
                                });
                            }
                            dh.setSupplierIds(existsSets);
                            dh.setSupplierList(supplierList);
                        }
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public Long countPromotionHead(String name, String promotionType, String startTime, String endTime, String promotionState) throws Exception {
        Long result = null;
        try {
            startTime = Tools.parseDayToTime(startTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            result = promotionHeadMapperEx.countsByPromotionHead(name, promotionType, startTime, endTime, promotionState);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertPromotionHead(JSONObject obj, HttpServletRequest request) throws Exception {
//        PromotionHead promotionHead = JSONObject.parseObject(obj.toJSONString(), PromotionHead.class);
//        promotionHead.setUploadFlag("0");
//        try {
//            promotionHeadMapper.insertSelective(promotionHead);
//        } catch (Exception e) {
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
//        //新增编辑之前的重复判断
//
//        promotionItemSave(obj, promotionHead.getId(), "insert",promotionHead.getPromotionType(),promotionHead.getCustom11());
//        if (promotionHead.getHoldDepot().equals(BusinessConstants.PROMOTION_HEAD_HOLD)) {
//            promotionDepotSave(obj, promotionHead.getId(), "insert");
//        }
//         if (promotionHead.getCustom11() !=null && 3==promotionHead.getCustom11()) {
//            promotionSupplierSave(obj, promotionHead.getId(), "insert");
//        }
//        logService.insertLog("促销",
//                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(promotionHead.getPromotionName()).toString(), request);
        return 1;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updatePromotionHead(JSONObject obj, HttpServletRequest request) throws Exception {
//        PromotionHead promotionHead = JSONObject.parseObject(obj.toJSONString(), PromotionHead.class);
//        promotionHead.setUploadFlag("0");
//        promotionHeadMapper.updateByPrimaryKeySelective(promotionHead);
//        promotionItemSave(obj, promotionHead.getId(), "update",promotionHead.getPromotionType(),promotionHead.getCustom11());
//        if (promotionHead.getHoldDepot().equals(BusinessConstants.PROMOTION_HEAD_HOLD)) {
//            promotionDepotSave(obj, promotionHead.getId(), "update");
//        }
//         if (promotionHead.getCustom11() !=null && 3==promotionHead.getCustom11()) {
//            promotionSupplierSave(obj, promotionHead.getId(), "update");
//        }
//        logService.insertLog("促销",
//                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(promotionHead.getPromotionName()).toString(), request);
        return 1;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deletePromotionHead(String id, HttpServletRequest request) throws Exception {
        PromotionHead promotionHead = new PromotionHead();
        promotionHead.setId(id);
        promotionHead.setDeleteFlag("1");
        promotionHead.setUploadFlag("0");
        int result = 0;
        try {
            result = promotionHeadMapper.updateByPrimaryKeySelective(promotionHead);
            logService.insertLog("促销",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(id).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeletePromotionHead(String ids, HttpServletRequest request) throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        PromotionHeadExample example = new PromotionHeadExample();
        example.createCriteria().andIdIn(idList);
        PromotionHead promotionHead = new PromotionHead();
        promotionHead.setDeleteFlag("1");
        promotionHead.setUploadFlag("0");
        int result = 0;
        try {
            result = promotionHeadMapper.updateByExampleSelective(promotionHead, example);
            logService.insertLog("促销", "批量删除,id集:" + ids, request);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public int checkIsNameExist(String id, String name) throws Exception {
        PromotionHeadExample example = new PromotionHeadExample();
        example.createCriteria().andIdNotEqualTo(id).andPromotionNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<PromotionHead> list = null;
        try {
            list = promotionHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list == null ? 0 : list.size();
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void promotionItemSave(JSONObject obj, String id, String type,Integer promotionType,Integer custom11) throws Exception {
        Set<String> existsSets = Sets.newHashSet();
        if ("update".equals(type)) {
            List<PromotionItem> existsVOS = getItemByHeaderId(id);
            existsVOS.forEach(existsVO -> {
                existsSets.add(existsVO.getId());
            });
        }
        //先处理增加，修改
        List<PromotionItem> itemList = JSONObject.parseArray(obj.getJSONArray("meList").toJSONString(), PromotionItem.class);
        if (itemList.size() > 0) {
            for (PromotionItem item : itemList) {
                item.setHeaderId(id);
                item.setUploadFlag("0");
                if (existsSets.contains(item.getId())) {
                    existsSets.remove(item.getId());
                    promotionItemMapper.updateByPrimaryKeySelective(item);
                }else {
                    item.setId(IdUtils.getUUID());
//                    PromotionHead head = checkMaterialWithHeaderId(item.getMaterialId(), item.getMeId(), item.getCommodityUnit(),promotionType,id,custom11);
//                    if (head != null) {
//                        throw new BusinessRunTimeException(ExceptionConstants.DATA_READ_FAIL_CODE,"zh".equals(systemConfigService.getLanCode()) ?  "商品条码" + item.getBarCode() + "已存在其他促销活动" : "There are other promotions for the product barcode" + item.getBarCode());
//                    }
                    promotionItemMapper.insertSelective(item);
                }
                if (promotionType==3){
//                    promotionGiftSave(item.getPromotionGiftList(),item.getId());
                    promotionGiftSave(obj,item.getId(),type);
                }
            }
        }else {
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "促销活动商品不能为空");
        }
        //然后 删除
        for (String itemId : existsSets) {
            promotionHeadMapperEx.batchDeletePromotionItemById(itemId);
        }
    }

//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public void promotionGiftSave(List<PromotionGift> promotionGifts, String id) throws Exception {
//        Set<String> existsSets = Sets.newHashSet();
//        List<PromotionGift> existsVOS = getGiftByItemId(id);
//        existsVOS.stream().forEach(existsVO -> {
//            existsSets.add(existsVO.getId());
//        });
//
//        if (promotionGifts != null) {
//            for (PromotionGift item : promotionGifts) {
//                item.setItemId(id);
//                if (existsSets.contains(item.getId())) {
//                    existsSets.remove(item.getId());
//                    promotionGiftMapper.updateByPrimaryKeySelective(item);
//                    continue;
//                }
//                item.setId(IdUtils.getUUID());
//                promotionGiftMapper.insertSelective(item);
//            }
//        }else {
//            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
//                    "zh".equals(systemConfigService.getLanCode()) ? "赠品不能为空" : "Giveaway cannot be empty");
//        }
//        //然后 删除
//        for (String itemId : existsSets) {
//            promotionHeadMapperEx.batchDeletePromotionGiftByItemId(itemId);
//        }
//    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void promotionGiftSave(JSONObject obj, String id, String type) throws Exception {
        Set<String> existsSets = Sets.newHashSet();
        PromotionItem promotionItem = promotionItemMapper.selectByPrimaryKey(id);
        if ("update".equals(type)) {
            List<PromotionGift> existsVOS = getGiftByItemId(id);
            existsVOS.stream().forEach(existsVO -> {
                existsSets.add(existsVO.getId());
            });
        }

        List<PromotionGift> giftList = JSONObject.parseArray(obj.getJSONArray("promotionGiftList").toJSONString(), PromotionGift.class);
        List<PromotionGift> itemList=new ArrayList<PromotionGift>();
        if (giftList!=null){
            for (PromotionGift item : giftList){
                if (promotionItem.getMaterialId().equals(item.getMaterialId())){
                    itemList.add(item);
                }
            }
        }
        if (itemList.size() > 0) {
            for (PromotionGift item : itemList) {
                item.setItemId(id);
                item.setUploadFlag("0");
                if (existsSets.contains(item.getId())) {
                    existsSets.remove(item.getId());
                    promotionGiftMapper.updateByPrimaryKeySelective(item);
                    continue;
                }
                item.setId(IdUtils.getUUID());
                promotionGiftMapper.insertSelective(item);
            }
        }else {
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? "赠品不能为空" : "Giveaway cannot be empty");
        }
        //然后 删除
        for (String itemId : existsSets) {
            promotionHeadMapperEx.batchDeletePromotionGiftByItemId(itemId);
        }
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void promotionDepotSave(JSONObject obj, String id, String type) throws Exception {
        Set<String> existsSets = Sets.newHashSet();
        if ("update".equals(type)) {
            List<PromotionDepot> existsVOS = getDepotByHeaderId(id);
            existsVOS.stream().forEach(existsVO -> {
                existsSets.add(existsVO.getId());
            });
        }
        //先处理增加，修改
        List<PromotionDepot> itemList = JSONObject.parseArray(obj.getJSONArray("depotList").toJSONString(), PromotionDepot.class);
        if (itemList != null && itemList.size() > 0) {
            for (PromotionDepot item : itemList) {
                item.setHeaderId(id);
                item.setUploadFlag("0");
                if (existsSets.contains(item.getId())) {
                    existsSets.remove(item.getId());
                    promotionDepotMapper.updateByPrimaryKeySelective(item);
                    continue;
                }
                item.setId(IdUtils.getUUID());
                promotionDepotMapper.insertSelective(item);
            }
        }else {
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? "适用仓库为部分仓库时，仓库不能为空" : "When the applicable warehouse is a partial warehouse, the warehouse cannot be empty");
        }
        //然后 删除
        for (String headerId : existsSets) {
            promotionHeadMapperEx.batchDeletePromotionDepotByHeaderId(headerId);
        }
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void promotionSupplierSave(JSONObject obj, String id, String type) throws Exception {
        Set<String> existsSets = Sets.newHashSet();
        if ("update".equals(type)) {
            List<PromotionSupplier> existsVOS = getSupplierByHeaderId(id);
            existsVOS.stream().forEach(existsVO -> {
                existsSets.add(existsVO.getId());
            });
        }
        //先处理增加，修改
        List<PromotionSupplier> itemList = JSONObject.parseArray(obj.getJSONArray("supplierList").toJSONString(), PromotionSupplier.class);
        if (itemList != null && itemList.size() > 0) {
            for (PromotionSupplier item : itemList) {
                item.setHeaderId(id);
                item.setUploadFlag("0");
                if (existsSets.contains(item.getId())) {
                    existsSets.remove(item.getId());
                    promotionSupplierMapper.updateByPrimaryKeySelective(item);
                    continue;
                }
                item.setId(IdUtils.getUUID());
                promotionSupplierMapper.insertSelective(item);
            }
        }else {
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? "适用客户为部分客户时，客户不能为空" : "When the applicable customers are some customers, the customer cannot be empty");
        }
        //然后 删除
        for (String oldId : existsSets) {
            promotionHeadMapperEx.batchDeletePromotionSupplierById(oldId);
        }
    }

    /**
     * @Author: wy
     * @Description: 根据表头获取表体列表
     * @DateTime: 2022/8/1 15:56
     * @Params:
     * @Return
     */
    public List<PromotionItem> getItemByHeaderId(String id) throws Exception {
        List<PromotionItem> list = null;
        try {
            PromotionItemExample example = new PromotionItemExample();
            example.createCriteria().andHeaderIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = promotionItemMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    /**
    * @Author: wy
    * @Description: 获取明细
    * @DateTime: 2022/8/9 18:41
    * @Params:
    * @Return
    */
    public List<PromotionItem> getItemDetails(String id) throws Exception {
        List<PromotionItem> list = null;
        try {
            PromotionItemExample example = new PromotionItemExample();
            example.createCriteria().andHeaderIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = promotionItemMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    /**
     * @Author: wy
     * @Description: 根据表头获取仓库列表
     * @DateTime: 2022/8/1 15:56
     * @Params:
     * @Return
     */
    public List<PromotionDepot> getDepotByHeaderId(String id) throws Exception {
        List<PromotionDepot> list = null;
        try {
            PromotionDepotExample example = new PromotionDepotExample();
            example.createCriteria().andHeaderIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = promotionDepotMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    /**
     * @Author: wy
     * @Description: 根据表体获取赠品列表
     * @DateTime: 2022/8/1 15:56
     * @Params:
     * @Return
     */
    public List<PromotionGift> getGiftByItemId(String id) throws Exception {
        List<PromotionGift> list = null;
        try {
            PromotionGiftExample example = new PromotionGiftExample();
            example.createCriteria().andItemIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = promotionGiftMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    /**
     * @Author: wy
     * @Description: 根据表头获取客户列表
     * @DateTime: 2022/8/1 15:56
     * @Params:
     * @Return
     */
    public List<PromotionSupplier> getSupplierByHeaderId(String id) throws Exception {
        List<PromotionSupplier> list = null;
        try {
            PromotionSupplierExample example = new PromotionSupplierExample();
            example.createCriteria().andHeaderIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = promotionSupplierMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    /**
     * @Author: wy
     * @Description: 根据商品信息获取促销信息
     * @DateTime: 2022/8/3 9:44
     * @Params:
     * @Return
     */
//    public PromotionVoDetail checkMaterialWithCodeExist(String materialId, String meId, String unit,Integer promotionType,Integer custom11) {
//        List<PromotionVoDetail> head = null;
//        try {
//            head = promotionHeadMapperEx.getPromotionHeadByCode(materialId, meId, unit,promotionType,custom11);
//        } catch (Exception e) {
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
//        if (head.size() > 0) {
//            return head.get(0);
//        }
//        return null;
//    }
    public PromotionVoDetail checkMaterialWithCodeExist(String materialId, String meId, String unit,Integer promotionType,Integer holdSupplier,Integer custom11, String organId) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.getPromotionHeadByCode(materialId, meId, unit,promotionType,holdSupplier,custom11,organId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (null != head && head.size() > 0) {
            return head.get(0);
        }
        return null;
    }


    public PromotionVoDetail checkMaterialWithHeaderId(String materialId, String meId, String unit,Integer promotionType,
                                                       String headerId,Integer custom11) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.checkMaterialWithHeaderId(materialId, meId, unit,promotionType,headerId,custom11);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (head.size() > 0) {
            return head.get(0);
        }
        return null;
    }
    /**
     * @Author: wy
     * @Description: 根据商品Id获取满减信息
     * @DateTime: 2022/8/3 9:44
     * @Params:
     * @Return
     */
    public PromotionVoDetail getPromotionHeadById(String materialId,Integer custom11,Integer holdSupplier,String organId) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.getPromotionHeadById(materialId,custom11,holdSupplier,organId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (head.size() > 0) {
            return head.get(0);
        }
        return null;
    }
    /**
     * @Author: wy
     * @Description: 根据商品Id获取满赠信息
     * @DateTime: 2022/8/3 9:44
     * @Params:
     * @Return
     */
    public PromotionVoDetail getPromotionGiveById(String materialId,String materialUnit,Integer custom11,Integer holdSupplier,String organId) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.getPromotionGiveById(materialId,materialUnit,custom11,holdSupplier,organId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (head.size() > 0) {
            return head.get(0);
        }
        return null;
    }

    // 零售根据商品Id获取满赠信息
    public PromotionVoDetail lsGetPromotionGiveById(String materialId) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.lsGetPromotionGiveById(materialId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (null != head && head.size() > 0) {
            return head.get(0);
        }
        return null;
    }
    // 零售根据商品Id获取满赠信息
    public PromotionVoDetail lsGetPromotionSpecialById(String materialExtendId,String materialId,Integer promotionType) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.lsGetPromotionSpecialById(materialExtendId,materialId,promotionType);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (null != head && head.size() > 0) {
            return head.get(0);
        }
        return null;
    }


    public boolean checkIsSupplierWithDepot(String headId, String supplierId, String depotId) throws Exception {
        List<PromotionDepot> depotByHeaderId = getDepotByHeaderId(headId);
        List<PromotionSupplier> supplierByHeaderId = getSupplierByHeaderId(headId);
        int depotInt = 0;
        int supplierInt = 0;
        for (PromotionDepot dep : depotByHeaderId) {
            if (dep.getDepotId().equals(depotId)) {
                depotInt = 1;
                break;
            }
        }
        for (PromotionSupplier sup : supplierByHeaderId) {
            if (sup.getSupplierId().equals(supplierId)) {
                supplierInt = 1;
                break;
            }
        }
        if (depotInt > 0 && supplierInt > 0) {
            return true;
        }
        return false;
    }

    public boolean checkIsSupplier(String headId, String supplierId) throws Exception {
        List<PromotionSupplier> supplierByHeaderId = getSupplierByHeaderId(headId);
        int supplierInt = 0;
        for (PromotionSupplier sup : supplierByHeaderId) {
            if (sup.getSupplierId().equals(supplierId)) {
                supplierInt = 1;
                break;
            }
        }
        if (supplierInt > 0) {
            return true;
        }
        return false;
    }

    public boolean checkIsDepot(String headId, String depotId) throws Exception {
        List<PromotionDepot> depotByHeaderId = getDepotByHeaderId(headId);
        int depotInt = 0;
        for (PromotionDepot dep : depotByHeaderId) {
            if (dep.getDepotId().equals(depotId)) {
                depotInt = 1;
                break;
            }
        }
        if (depotInt > 0) {
            return true;
        }
        return false;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int addPromotionHeadAndDetail(JSONObject obj, HttpServletRequest request) throws Exception {
        PromotionHead promotionHead = JSONObject.parseObject(obj.toJSONString(), PromotionHead.class);
        promotionHead.setId(IdUtils.getUUID());
        promotionHead.setCreateTime(new Date());
//        User userInfo=userService.getCurrentUser();
//        promotionHead.setCreator(userInfo==null?null:userInfo.getId());
        promotionHead.setUploadFlag("0");
        try {
            promotionHeadMapper.insertSelective(promotionHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        //新增编辑时的，重复判断
        checkMaterialWithSupplierId(obj,promotionHead.getPromotionType(),promotionHead.getCustom11(), promotionHead.getId(),promotionHead.getHoldSupplier());
        promotionItemSave(obj, promotionHead.getId(), "insert",promotionHead.getPromotionType(),promotionHead.getCustom11());
//        if (promotionHead.getHoldDepot().equals(BusinessConstants.PROMOTION_HEAD_HOLD)) {
//            promotionDepotSave(obj, promotionHead.getId(), "insert");
//        }
         if (promotionHead.getCustom11() !=null && 3==promotionHead.getCustom11()) {
             if (promotionHead.getHoldSupplier().equals(BusinessConstants.PROMOTION_HEAD_HOLD)){
                 promotionSupplierSave(obj, promotionHead.getId(), "insert");
             }
        }

        logService.insertLog("促销",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(promotionHead.getPromotionName()).toString(), request);
        return 1;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updatePromotionHeadAndDetail(JSONObject obj, HttpServletRequest request) throws Exception {
        PromotionHead promotionHead = JSONObject.parseObject(obj.toJSONString(), PromotionHead.class);
        promotionHead.setUploadFlag("0");
        promotionHeadMapper.updateByPrimaryKeySelective(promotionHead);
        //新增编辑时的，重复判断
        checkMaterialWithSupplierId(obj,promotionHead.getPromotionType(),promotionHead.getCustom11(), promotionHead.getId(),promotionHead.getHoldSupplier());
        promotionItemSave(obj, promotionHead.getId(), "update",promotionHead.getPromotionType(),promotionHead.getCustom11());
//        if (promotionHead.getHoldDepot().equals(BusinessConstants.PROMOTION_HEAD_HOLD)) {
//            promotionDepotSave(obj, promotionHead.getId(), "update");
//        }
         if (promotionHead.getCustom11() !=null && 3==promotionHead.getCustom11()) {
             if (promotionHead.getHoldSupplier().equals(BusinessConstants.PROMOTION_HEAD_HOLD)){
                 promotionSupplierSave(obj, promotionHead.getId(), "update");
             }else {
                 batchDeletePromotionSupplierByHeaderId(promotionHead.getId());
             }

        }

        logService.insertLog("促销",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(promotionHead.getPromotionName()).toString(), request);
        return 1;
    }


    public void checkMaterialWithSupplierId(JSONObject obj, Integer promotionType,Integer custom11,String headerId,Integer holdSupplier) {
        List<CheckPromotionMaterialWithSupplier> head = null;
        List<PromotionItem> itemList = JSONObject.parseArray(obj.getJSONArray("meList").toJSONString(), PromotionItem.class);

        for (PromotionItem promotionItem : itemList) {
            head = promotionHeadMapperEx.checkMaterialWithSupplierId(promotionType,custom11,headerId,1,promotionItem.getMaterialId(),null);
            if (head != null && head.size()>0) {
                CheckPromotionMaterialWithSupplier materialWithSupplier = head.get(0);
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode())
                                ? materialWithSupplier.getMaterialName()+materialWithSupplier.getStandard()+"已存在单据编号"+materialWithSupplier.getPromotionNo()
                                : materialWithSupplier.getMaterialName()+materialWithSupplier.getStandard()+"has document number"+materialWithSupplier.getPromotionNo());
            }
        }

        if (holdSupplier.equals(BusinessConstants.PROMOTION_HEAD_HOLD)){
            List<PromotionSupplier> supplierList = JSONObject.parseArray(obj.getJSONArray("supplierList").toJSONString(), PromotionSupplier.class);
            if (supplierList == null) {
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "适用客户为部分客户时，客户不能为空" : "When the applicable customers are some customers, the customer cannot be empty");
            }
            List<String> materialIdList = itemList.stream()
                    .map(PromotionItem::getMaterialId)
                    .collect(Collectors.toList());
            List<String> supplierIdList = supplierList.stream()
                    .map(PromotionSupplier::getSupplierId)
                    .collect(Collectors.toList());
            for (String materialId:materialIdList){
                for (String supplierId:supplierIdList){
                    head = promotionHeadMapperEx.checkMaterialWithSupplierId(promotionType,custom11,headerId,2,materialId,supplierId);
                    if (head != null && head.size()>0) {
                        CheckPromotionMaterialWithSupplier materialWithSupplier = head.get(0);
                        throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                                "zh".equals(systemConfigService.getLanCode())
                                        ? materialWithSupplier.getMaterialName()+materialWithSupplier.getStandard()+"已存在单据编号"+materialWithSupplier.getPromotionNo()+"，客户："+materialWithSupplier.getSupplier()
                                        : materialWithSupplier.getMaterialName()+materialWithSupplier.getStandard()+"has document number"+materialWithSupplier.getPromotionNo()+"，customer："+materialWithSupplier.getSupplier());
                    }
                }
            }

        }else {
            for (PromotionItem promotionItem : itemList) {
                head = promotionHeadMapperEx.checkMaterialWithSupplierId(promotionType,custom11,headerId,2,promotionItem.getMaterialId(),null);
                if (head != null && head.size()>0) {
                    CheckPromotionMaterialWithSupplier materialWithSupplier = head.get(0);
                    throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                            "zh".equals(systemConfigService.getLanCode())
                                    ? materialWithSupplier.getMaterialName()+materialWithSupplier.getStandard()+"已存在单据编号"+materialWithSupplier.getPromotionNo()+"，客户："+materialWithSupplier.getSupplier()
                                    : materialWithSupplier.getMaterialName()+materialWithSupplier.getStandard()+"has document number"+materialWithSupplier.getPromotionNo()+"，customer："+materialWithSupplier.getSupplier());
                }
            }
        }
    }

    public List<PromotionItemWithMaterial> getMaterialById(String id) throws Exception {
        List<PromotionItemWithMaterial> resList = new ArrayList<PromotionItemWithMaterial>();
        List<PromotionItemWithMaterial> list = null;
        try {
            list = promotionHeadMapperEx.getMaterialById(id);
            if (null != list) {
                for (PromotionItemWithMaterial dh : list) {
                    dh.setUnit(dh.getCommodityUnit());
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<PromotionDepot> getDepotId(String id) throws Exception {
        List<PromotionDepot> list = null;
        try {
            list = promotionHeadMapperEx.getDepotId(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<PromotionSupplier> getSupplierId(String id) throws Exception {
        List<PromotionSupplier> list = null;
        try {
            list = promotionHeadMapperEx.getSupplierId(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<PromotionGift> getGiftId(String id) throws Exception {
        List<PromotionGift> list = null;
        try {
            PromotionGiftExample example = new PromotionGiftExample();
            example.createCriteria().andItemIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = promotionGiftMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<PromotionGiftWithMaterial> getMaterialByGiftId(String id) throws Exception {
        List<PromotionGiftWithMaterial> resList = new ArrayList<PromotionGiftWithMaterial>();
        List<PromotionGiftWithMaterial> list = null;
        try {
            list = promotionHeadMapperEx.getMaterialByGiftId(id);
            if (null != list) {
                for (PromotionGiftWithMaterial dh : list) {
                    dh.setUnit(dh.getGiftMaterialUnit());
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetPromotionTenant(String ids,String syncTenantId) throws Exception {
        int result =0;
        List<String> idList = StringUtil.strToStringList(ids);
        PromotionHeadExample example=new PromotionHeadExample();
        example.createCriteria().andIdIn(idList);
        PromotionHead entity=new PromotionHead();
        entity.setSyncTenantId(syncTenantId);
        try{
            result=  promotionHeadMapper.updateByExampleSelective(entity, example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeletePromotionSupplierByHeaderId(String headerId) throws Exception {
        int result =0;
        PromotionSupplierExample example=new PromotionSupplierExample();
        example.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        PromotionSupplier entity=new PromotionSupplier();
        entity.setUploadFlag("0");
        entity.setDeleteFlag("1");
        try{
            result=  promotionSupplierMapper.updateByExampleSelective(entity, example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public PromotionVoDetail getSpecial(String materialId, Integer custom11, BigDecimal operNumber,Integer holdSupplier,String organId) {
        List<PromotionVoDetail> head = null;
        try {
            head = promotionHeadMapperEx.getSpecial(materialId,custom11,operNumber,holdSupplier,organId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (null != head && head.size() > 0) {
            return head.get(0);
        }
        return null;
    }
}
